package com.main.common.base.resp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.main.common.utils.exceptions.StackTraceLog;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Lin 2024/12/27
 * 响应结果体
 */
@Getter
@Setter
public class RespBody<T> {
    /**
     * 自定义业务码
     */
    private int code;
    /**
     * 自定义业务提示说明
     */
    private String message;
    /**
     * 自定义返回 数据结果集
     */
    private T body;
    /**
     *
     */
    private StackTraceLog stackTraceLog;

    public String toJson() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        } catch (Exception e) {
            stackTraceLog.saveStackTraceLog(e);
            return null;
        }
    }
    public RespBody() { }

    public RespBody(int code) {
        this.code = code;
    }

    public RespBody(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public RespBody(int code, String message, T body) {
        this.code = code;
        this.message = message;
        this.body = body;
    }

    public static RespBody<Void> ok() {
        return ok(null);
    }

    public static <T> RespBody<T> ok(T body) {
        return build(RespCode.OK, body);
    }

    public static RespBody<ErrorBody> error(int code, String message, ErrorBody errorBody) {
        return build(code, message, errorBody);
    }

    public static RespBody<ErrorBody> error(ResultCode resultCode, ErrorBody errorBody) {
        return build(resultCode.getCode(), resultCode.getMessage(), errorBody);
    }

    public static RespBody<ErrorBody> error(ResultCode resultCode, String message, ErrorBody errorBody) {
        return build(resultCode.getCode(), message, errorBody);
    }

    public static <T> RespBody<T> fail(String message) {
        return fail(RespCode.FAIL, message, null);
    }

    public static <T> RespBody<T> fail(ResultCode resultCode) {
        return fail(resultCode, resultCode.getMessage(), null);
    }

    public static <T> RespBody<T> fail(ResultCode resultCode, String message, T data) {
        return build(resultCode.getCode(), message, data);
    }


    public static <T> RespBody<T> build(ResultCode resultCode, T body) {
        return build(resultCode.getCode(), resultCode.getMessage(), body);
    }

    /**
     * 以上所有构建均调用此底层方法
     *
     * @param stateCode 状态值
     * @param message   返回消息
     * @param body      返回数据体
     */
    public static <T> RespBody<T> build(int stateCode, String message, T body) {
        return new RespBody<>(stateCode, message, body);
    }

}
